import { useState } from 'react'
import { Wrapper } from './FileBlob.styled'

/**
 
  URL.createObjectURL(blob)         // blob url
  FileReader.readAsDataURL(file);   // data url

  // url props
  <a href={url}> ... </a>
  <img src={url} />
  <iframe src={url}></iframe>

  // <a>
  target="_blank"
  download

 */
type TYPE = 'text'|'image'|'';
export const Demo = () => {
  const [type, setType] = useState<TYPE>('');
  const [objUrl, setObjUrl] = useState<any>(null)

  const onFetch = (type:TYPE, filename:string) => () => {
    fetch(filename)
    .then((response) => {
      return response.blob()
    })
    .then(async (result: Blob) => {
      console.log(result)
      // setObjUrl(URL.createObjectURL(result))
      // setType(type)
      const fr = new FileReader();
      fr.onload=((e:any) => {
        console.log(e.target.result)
        setObjUrl(e.target.result);
        setType(type)
      })
      fr.readAsDataURL(result);
    })
    .catch((err) => {
      console.error(err)
    })
  }
  return (
    <Wrapper>
      <textarea value={objUrl}></textarea>
      <button onClick={onFetch('text',  '/file.txt')}>fetch text file</button>
      <button onClick={onFetch('image', '/monkey.jpg')}>fetch image file</button>
      { !!objUrl &&
        <a href={objUrl} target="_blank" >link</a>
      }
      { !!objUrl && (type === 'text') &&
        <iframe src={objUrl} width="200px"></iframe>
      }
      { (type=== 'image') && !!objUrl &&
        <img src={objUrl} alt="img" width={'200px'} />
      }
    </Wrapper>
  )
}
